package com.yjz.middleware.netty;

import com.yjz.middleware.netty.codec.StudentCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
 * @desc:  学生协议服务端
 * @author: yuanjz@deepblueai.com
 * @date: 2019/5/9 11:16
 */
public class StudentProtocolServer {
  private int port;

  public StudentProtocolServer(int port) {
    this.port = port;
  }

  public static void main(String[] args) {
    int port = 8012;
    new StudentProtocolServer(port).run();
  }

  public void run() {
    NioEventLoopGroup boss = new NioEventLoopGroup();
    NioEventLoopGroup work = new NioEventLoopGroup();
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(boss, work)
      .channel(NioServerSocketChannel.class)
      .childHandler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel sc) throws Exception {
          sc.pipeline().addLast(new StudentCodec()).addLast(new StudentProtocolServerHandler());
        }
      }).option(ChannelOption.SO_BACKLOG, 128)
      .childOption(ChannelOption.SO_KEEPALIVE, true);
    ChannelFuture f = null;
    try {
      f = bootstrap.bind(port).sync();
      f.channel().closeFuture().sync();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      boss.shutdownGracefully();
      work.shutdownGracefully();
    }
  }
}
